package com.yufei.toolinterface.util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yufei.infoExtractor.core.CollectionElementType;
import com.yufei.infoExtractor.util.CommonUtil;
import com.yufei.infoExtractor.util.ExceptionUtil;

/**
 * @author jasstion
   2012-11-27
   用于产生经过封装或者数据组装的swing组件，全部为静态方法，此类不可继承只可以加入新的方法
 *
 */
public final class ComponentFactory {
	static Log mLog = LogFactory.getLog(ComponentFactory.class);

	public static JDialog createDialogForCollectionInformation(final JDialog parent, boolean modal,final Collection collection,final Class elementType) {
		final JDialog dialog=new JDialog(parent, modal);
		 dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
		dialog.setTitle("集合信息显示");
		JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
		jScrollPane1.setSize(DialogUtil.DialogWidth, DialogUtil.DialogHeight);
	   
		try {
			 final JTable jTable1 = ComponentFactory.createJTableForCollectionInformation(dialog, collection, elementType);
			 
			 
			 
			 
			 jScrollPane1.setViewportView(jTable1);
			    
			    
			    
			    
			    
			    
			    dialog.add(jScrollPane1);
			  
			    ButtonJPanel  buttonJPanel=new ButtonJPanel();
			    JButton saveButton=buttonJPanel.getSaveButton();
			    JButton deleteButton=buttonJPanel.getDeleteButton();
			    JButton addButton=buttonJPanel.getAddButton();
			   
	
	
	
			    //dialog.add(saveButton);
			  //  dialog.add(deleteButton);
			    dialog.add(buttonJPanel);
	
			    dialog.setModal(modal);
			    saveButton.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						// TODO Auto-generated method stub
						Collection collection1=null;
						collection1=TableModelUtil.convertVectorToEntity(elementType,(DefaultTableModel)jTable1.getModel());
						collection.removeAll(collection);
				        collection.addAll(collection1);
						DialogUtil.popUpDialog("保存成功！");
					}
				});
			    deleteButton.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						// TODO Auto-generated method stub
						
						int[] selectedRows=jTable1.getSelectedRows();
						for(int selectedRow:selectedRows){
							  ((DefaultTableModel)jTable1.getModel()).removeRow(selectedRow);
	
						}
						Collection collection1=null;
						collection1=TableModelUtil.convertVectorToEntity(elementType,(DefaultTableModel)jTable1.getModel());
						collection.removeAll(collection);
				        collection.addAll(collection1);
						DialogUtil.popUpDialog("删除成功！");
					}
				});
			    addButton.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						// TODO Auto-generated method stub
						TableModel model = jTable1.getModel();
						try {
							((DefaultTableModel) model).addRow(TableModelUtil.convertEntityToVector(elementType.newInstance(), (AbstractTableModel) model));
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
	
	
						
					}
					
				});
	
		} catch (Exception e1) {
			// TODO Auto-generated catch block
	  mLog.info(ExceptionUtil.getExceptionDetailsMessage(e1));
		} 
	
	    		
	
	
	   
	   // dialog.setLocationRelativeTo(dialog);
	
	   // dialog.setVisible(true);
	
		return dialog;
	}

	/**
	 * @param parent
	 * @param collection
	 * @param elementType
	 *            :用于表示此集合类中的元素类型（已处理此集合类为空的时候得不到里面的元素类型从而无法确定列表的问题）
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public static JTable createJTableForCollectionInformation(
			final JDialog parent, Collection collection, final Class elementType)
			throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {
		final JTable jTable1 = new javax.swing.JTable();
		// 获取集合中的对象class
	
		AbstractTableModel tableModel = TableModelUtil.getTableModel(elementType);
		// 组装数据
	
		jTable1.setModel(tableModel);
		if (collection.size() != 0) {
			Iterator iterator = collection.iterator();
			Vector vector = null;
			int rowNumber = 0;
			Object entity = null;
			while (iterator.hasNext()) {
				entity = iterator.next();
				try {
					vector = TableModelUtil.convertEntityToVector(entity, tableModel);
				} catch (Exception e) {
					ExceptionUtil.getExceptionDetailsMessage(e);
				}
				((DefaultTableModel) tableModel).insertRow(rowNumber++, vector);
	
			}
		}
	
		// search for the cloumn whose value is customerObj or Collection
	
		List<Field> fields = CommonUtil.getAllDeclareFields(elementType);// entity.getDeclaredFields();
		// Field[] fields = entity.getFields();
	
		TableColumn tableColumn = null;
	
		for (Field field : fields) {
			Class fieldCla = field.getType();
			if (CommonUtil.isCustomerObjType(fieldCla)) {
				tableColumn = jTable1.getColumn(field.getName());
				if(parent!=null){
					ButtonTableCellRenderer colorColumnRenderer = new ButtonTableCellRenderer(
							new EntityButton(null, "进入内容-->", parent));
					tableColumn.setCellRenderer(colorColumnRenderer);

				}
				
				// 此列设置为不可编辑
	
			}
			if (CommonUtil.isCollection(fieldCla)) {
				tableColumn = jTable1.getColumn(field.getName());
				if(parent!=null){
					ButtonTableCellRenderer colorColumnRenderer = new ButtonTableCellRenderer(
							new ListButton(null, "进入列表-->", parent, null));
		
					tableColumn.setCellRenderer(colorColumnRenderer);
				}
				
			}
		}
	if(parent!=null){
		jTable1.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent mouseEvent) {
				int row = jTable1.rowAtPoint(mouseEvent.getPoint());
				int col = jTable1.columnAtPoint(mouseEvent.getPoint());
				Object entity = jTable1.getValueAt(row, col);
	
				if (entity == null) {
					return;
				}
				if (CommonUtil.isCollection(entity.getClass())) {
	
					Class subElementType = null;
					try {
						CollectionElementType annotation = CommonUtil
								.getFieldByFieldName(elementType,
										jTable1.getColumnName(col))
								.getAnnotation(CollectionElementType.class);
						;
						subElementType = annotation.type();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						TableModelUtil.mLog.info(ExceptionUtil.getExceptionDetailsMessage(e));
					}
					JDialog dialog = createDialogForCollectionInformation(parent,
									false, (Collection) entity, subElementType);
					dialog.pack();
					dialog.setVisible(true);
				}
				if (CommonUtil.isCustomerObjType(entity.getClass())) {
					JDialog dialog = DialogUtil.CreateDialogForCustomerObj(
							parent, false, entity);
					dialog.pack();
					dialog.setVisible(true);
				}
	
			}
		});
	}
		
		return jTable1;
	
	}
	

}
